Popular Searches
Popular Course Categories
Popular Courses

Building Selenium Scripts

Building Selenium Scripts

Selenium with Python

<div class="selenium-notes">

<h1>Building Selenium Scripts with Python</h1>

<p>Building Selenium Scripts means creating Python programs that use Selenium WebDriver to automate web browsers and perform actions such as opening websites, locating web elements, entering data, clicking buttons, navigating between pages, validating results, handling dynamic content, and closing the browser.</p>

<p>A Selenium script generally follows a structured flow: start the WebDriver session, open the application, locate elements, perform actions, validate expected results, handle synchronization and exceptions, and finally close the browser.</p>

<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is a Selenium Script?</h2>

<p>A Selenium script is a Python program that controls a web browser through Selenium WebDriver. The script can automate repetitive browser tasks and can also be used to execute functional and regression tests against web applications.</p>

<p>Instead of manually opening a browser, navigating to a website, entering information, clicking buttons, and checking results, Selenium allows these operations to be written as executable Python instructions.</p>

<h3>Basic Selenium Script Flow</h3>

<pre><code>Start

  |

  v

Import Selenium

  |

  v

Create WebDriver

  |

  v

Open Browser

  |

  v

Navigate to URL

  |

  v

Locate Web Elements

  |

  v

Perform Actions

  |

  v

Validate Results

  |

  v

Handle Exceptions

  |

  v

Close Browser

  |

  v

End</code></pre>

<h2>2. Why Build Selenium Scripts?</h2>

<p>Selenium scripts are useful when web application testing requires repetitive and reliable browser interactions.</p>

<ul>

<li>Automate repetitive browser tasks.</li>

<li>Reduce manual testing effort.</li>

<li>Execute functional test cases.</li>

<li>Support regression testing.</li>

<li>Validate user workflows.</li>

<li>Perform data-driven testing.</li>

<li>Run tests repeatedly.</li>

<li>Support CI/CD automation.</li>

<li>Generate repeatable test results.</li>

<li>Improve test coverage.</li>

</ul>

<h2>3. Components of a Selenium Script</h2>

<p>A well-structured Selenium script normally contains several important components.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Component</th><th>Purpose</th></tr>

<tr><td>Import statements</td><td>Load Selenium and Python libraries.</td></tr>

<tr><td>WebDriver</td><td>Controls the browser.</td></tr>

<tr><td>URL</td><td>Specifies the application page.</td></tr>

<tr><td>Locators</td><td>Identify web elements.</td></tr>

<tr><td>WebElement operations</td><td>Perform actions such as click and send_keys.</td></tr>

<tr><td>Waits</td><td>Synchronize the script with application state.</td></tr>

<tr><td>Assertions</td><td>Validate expected behavior.</td></tr>

<tr><td>Exception handling</td><td>Manage runtime failures.</td></tr>

<tr><td>Logging</td><td>Record execution information.</td></tr>

<tr><td>Teardown</td><td>Close the browser and release resources.</td></tr>

</table>

<hr>

<h2>4. Installing Selenium for Python</h2>

<p>The Selenium Python package can be installed using pip. Modern Selenium versions include Selenium Manager, which can automatically manage browser drivers in many common setups.</p>

<pre><code>pip install selenium</code></pre>

<p>To upgrade Selenium:</p>

<pre><code>pip install -U selenium</code></pre>

<h3>Verify Installation</h3>

<pre><code>python -c "import selenium; print(selenium.__version__)"</code></pre>

<h2>5. Creating the First Selenium Script</h2>

<p>The first step is to import Selenium and create a browser driver.</p>

<pre><code>from selenium import webdriver

 

driver = webdriver.Chrome()</code></pre>

<p>The Selenium Python API supports creating a Chrome WebDriver directly with <code>webdriver.Chrome()</code>. Selenium Manager can handle driver management for typical installations.</p>

<h2>6. Opening a Website</h2>

<p>The <code>get()</code> method navigates the browser to a specified URL.</p>

<pre><code>from selenium import webdriver

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com")

finally:

    driver.quit()</code></pre>

<h2>7. Understanding driver.get()</h2>

<p>The <code>driver.get()</code> method instructs WebDriver to navigate to the specified URL.</p>

<pre><code>driver.get("https://www.selenium.dev")</code></pre>

<p>A Selenium script can navigate to login pages, dashboards, product pages, search pages, checkout pages, administration panels, and other web application URLs.</p>

<hr>

<h2>8. Getting the Page Title</h2>

<p>The <code>title</code> property can be used to retrieve the current browser page title.</p>

<pre><code>title = driver.title

print(title)</code></pre>

<h3>Title Validation</h3>

<pre><code>assert "Selenium" in driver.title</code></pre>

<p>Assertions are useful for verifying that the application reached the expected page.</p>

<h2>9. Getting the Current URL</h2>

<pre><code>print(driver.current_url)</code></pre>

<p>URL validation can be useful after navigation or login.</p>

<pre><code>assert "/dashboard" in driver.current_url</code></pre>

<h2>10. Finding Web Elements</h2>

<p>Most Selenium scripts interact with web elements. Before performing an action, the script normally needs to locate the required element. Selenium's Python API uses <code>find_element()</code> together with the <code>By</code> locator strategies.</p>

<pre><code>from selenium.webdriver.common.by import By

 

username = driver.find_element(By.ID, "username")</code></pre>

<h2>11. Common Selenium Locators</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Locator</th><th>Example</th></tr>

<tr><td>ID</td><td><code>By.ID, "username"</code></td></tr>

<tr><td>NAME</td><td><code>By.NAME, "email"</code></td></tr>

<tr><td>CLASS_NAME</td><td><code>By.CLASS_NAME, "login-button"</code></td></tr>

<tr><td>TAG_NAME</td><td><code>By.TAG_NAME, "button"</code></td></tr>

<tr><td>LINK_TEXT</td><td><code>By.LINK_TEXT, "Login"</code></td></tr>

<tr><td>PARTIAL_LINK_TEXT</td><td><code>By.PARTIAL_LINK_TEXT, "Log"</code></td></tr>

<tr><td>CSS_SELECTOR</td><td><code>By.CSS_SELECTOR, "#username"</code></td></tr>

<tr><td>XPATH</td><td><code>By.XPATH, "//input[@id='username']"</code></td></tr>

</table>

<h2>12. Using ID Locator</h2>

<pre><code>username = driver.find_element(

    By.ID,

    "username"

)

username.send_keys("admin")</code></pre>

<h2>13. Using Name Locator</h2>

<pre><code>email = driver.find_element(

    By.NAME,

    "email"

)

email.send_keys("[email protected]")</code></pre>

<h2>14. Using CSS Selector</h2>

<pre><code>login_button = driver.find_element(

    By.CSS_SELECTOR,

    "button.login"

)

login_button.click()</code></pre>

<h2>15. Using XPath</h2>

<pre><code>login_button = driver.find_element(

    By.XPATH,

    "//button[@id='login']"

)

login_button.click()</code></pre>

<hr>

<h2>16. Entering Text with send_keys()</h2>

<p>The <code>send_keys()</code> method enters text into an input field.</p>

<pre><code>username = driver.find_element(By.ID, "username")

username.send_keys("admin")</code></pre>

<h2>17. Clearing Input Fields</h2>

<pre><code>username.clear()

username.send_keys("new_user")</code></pre>

<h2>18. Clicking Elements</h2>

<pre><code>login_button = driver.find_element(

    By.ID,

    "login"

)

login_button.click()</code></pre>

<h2>19. Reading Element Text</h2>

<pre><code>message = driver.find_element(

    By.ID,

    "message"

)

print(message.text)</code></pre>

<h2>20. Reading Attributes</h2>

<pre><code>value = element.get_attribute("value")

print(value)</code></pre>

<p>For example:</p>

<pre><code>placeholder = driver.find_element(

    By.ID,

    "username"

).get_attribute("placeholder")

 

print(placeholder)</code></pre>

<h2>21. Checking Element State</h2>

<pre><code>element = driver.find_element(By.ID, "submit")

 

print(element.is_displayed())

print(element.is_enabled())

print(element.is_selected())</code></pre>

<hr>

<h2>22. Building a Simple Login Script</h2>

<p>A login automation script generally performs the following sequence:</p>

<pre><code>Open Login Page

      |

      v

Find Username

      |

      v

Enter Username

      |

      v

Find Password

      |

      v

Enter Password

      |

      v

Find Login Button

      |

      v

Click Login

      |

      v

Wait for Dashboard

      |

      v

Validate Login

      |

      v

Close Browser</code></pre>

<h3>Login Script</h3>

<pre><code>from selenium import webdriver

from selenium.webdriver.common.by import By

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com/login")

 

    username = driver.find_element(

        By.ID,

        "username"

    )

 

    password = driver.find_element(

        By.ID,

        "password"

    )

 

    login_button = driver.find_element(

        By.ID,

        "login"

    )

 

    username.send_keys("admin")

    password.send_keys("admin123")

    login_button.click()

 

    print("Login action completed")

finally:

    driver.quit()</code></pre>

<hr>

<h2>23. Using Waits in Selenium Scripts</h2>

<p>Modern web applications frequently load content asynchronously. Therefore, a Selenium script should synchronize its actions with the state of the browser rather than assuming that every element is immediately ready.</p>

<h3>Explicit Wait Example</h3>

<pre><code>from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

login_button = WebDriverWait(

    driver,

    10

).until(

    EC.element_to_be_clickable(

        (By.ID, "login")

    )

)

 

login_button.click()</code></pre>

<h2>24. Why Explicit Waits are Useful</h2>

<ul>

<li>Handle dynamic elements.</li>

<li>Reduce timing-related failures.</li>

<li>Wait for specific application conditions.</li>

<li>Improve script reliability.</li>

<li>Avoid unnecessary fixed delays.</li>

</ul>

<h2>25. Avoiding Hardcoded sleep()</h2>

<p>A fixed sleep pauses for a predetermined amount of time regardless of whether the application is ready.</p>

<pre><code>import time

 

time.sleep(5)

 

driver.find_element(

    By.ID,

    "login"

).click()</code></pre>

<p>A condition-based wait is generally more appropriate when the required application state can be expressed explicitly.</p>

<pre><code>login = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable(

        (By.ID, "login")

    )

)

 

login.click()</code></pre>

<hr>

<h2>26. Using Assertions</h2>

<p>Assertions verify whether the actual result matches the expected result.</p>

<pre><code>assert "Dashboard" in driver.title</code></pre>

<h3>Message Assertion</h3>

<pre><code>message = driver.find_element(

    By.ID,

    "message"

).text

 

assert message == "Login successful"</code></pre>

<h2>27. Soft Validation with Conditions</h2>

<pre><code>if "Dashboard" in driver.current_url:

    print("Login successful")

else:

    print("Login failed")</code></pre>

<p>In a real test framework, assertions are normally preferred when the condition represents a required test result.</p>

<hr>

<h2>28. Handling Checkboxes</h2>

<pre><code>terms = driver.find_element(

    By.ID,

    "terms"

)

 

if not terms.is_selected():

    terms.click()</code></pre>

<h2>29. Handling Radio Buttons</h2>

<pre><code>male = driver.find_element(

    By.ID,

    "male"

)

 

if not male.is_selected():

    male.click()</code></pre>

<h2>30. Handling Dropdowns</h2>

<p>For a standard HTML <code>&lt;select&gt;</code> element, Selenium provides the <code>Select</code> helper.</p>

<pre><code>from selenium.webdriver.support.ui import Select

 

country = Select(

    driver.find_element(By.ID, "country")

)

 

country.select_by_visible_text("India")</code></pre>

<p>Other selection methods include:</p>

<pre><code>country.select_by_value("in")

country.select_by_index(0)</code></pre>

<h2>31. Handling Keyboard Actions</h2>

<pre><code>from selenium.webdriver.common.keys import Keys

 

search = driver.find_element(

    By.NAME,

    "q"

)

 

search.send_keys("Selenium")

search.send_keys(Keys.ENTER)</code></pre>

<hr>

<h2>32. Handling Links</h2>

<pre><code>documentation = driver.find_element(

    By.LINK_TEXT,

    "Documentation"

)

 

documentation.click()</code></pre>

<h2>33. Handling Multiple Elements</h2>

<p>Use <code>find_elements()</code> when multiple matching elements are expected.</p>

<pre><code>products = driver.find_elements(

    By.CLASS_NAME,

    "product"

)

 

print("Products:", len(products))

 

for product in products:

    print(product.text)</code></pre>

<h2>34. Finding Child Elements</h2>

<pre><code>form = driver.find_element(

    By.ID,

    "login-form"

)

 

inputs = form.find_elements(

    By.TAG_NAME,

    "input"

)

 

for field in inputs:

    print(field.get_attribute("name"))</code></pre>

<hr>

<h2>35. Navigation Commands</h2>

<p>Selenium scripts can navigate between pages using browser navigation commands.</p>

<pre><code>driver.get("https://example.com")

driver.back()

driver.forward()

driver.refresh()</code></pre>

<h2>36. Opening a New URL</h2>

<pre><code>driver.get(

    "https://example.com/products"

)</code></pre>

<h2>37. Browser Window Management</h2>

<pre><code>driver.maximize_window()</code></pre>

<p>Other useful operations include:</p>

<pre><code>driver.minimize_window()

driver.fullscreen_window()</code></pre>

<h2>38. Window Handles</h2>

<pre><code>print(driver.current_window_handle)

print(driver.window_handles)</code></pre>

<h3>Switching Windows</h3>

<pre><code>original_window = driver.current_window_handle

 

for handle in driver.window_handles:

    if handle != original_window:

        driver.switch_to.window(handle)

        break</code></pre>

<hr>

<h2>39. Handling Frames</h2>

<p>When a web element exists inside an iframe, the script must switch into the appropriate frame before interacting with its contents.</p>

<pre><code>driver.switch_to.frame(

    driver.find_element(

        By.ID,

        "payment-frame"

    )

)

 

card = driver.find_element(

    By.ID,

    "card-number"

)

 

card.send_keys("4111111111111111")

 

driver.switch_to.default_content()</code></pre>

<h3>Using Explicit Wait with Frame</h3>

<pre><code>WebDriverWait(driver, 10).until(

    EC.frame_to_be_available_and_switch_to_it(

        (By.ID, "payment-frame")

    )

)</code></pre>

<hr>

<h2>40. Handling Alerts</h2>

<pre><code>alert = driver.switch_to.alert

 

print(alert.text)

alert.accept()</code></pre>

<h3>Dismiss Alert</h3>

<pre><code>alert.dismiss()</code></pre>

<h3>Enter Alert Text</h3>

<pre><code>alert.send_keys("Test data")

alert.accept()</code></pre>

<h2>41. Waiting for an Alert</h2>

<pre><code>alert = WebDriverWait(driver, 10).until(

    EC.alert_is_present()

)

 

alert.accept()</code></pre>

<hr>

<h2>42. Handling Cookies</h2>

<pre><code>driver.add_cookie({

    "name": "test_cookie",

    "value": "selenium"

})</code></pre>

<h3>Get Cookies</h3>

<pre><code>cookies = driver.get_cookies()

 

for cookie in cookies:

    print(cookie)</code></pre>

<h3>Delete Cookies</h3>

<pre><code>driver.delete_all_cookies()</code></pre>

<hr>

<h2>43. JavaScript Execution</h2>

<p>Selenium scripts can execute JavaScript when browser-level interaction requires it.</p>

<pre><code>title = driver.execute_script(

    "return document.title;"

)

 

print(title)</code></pre>

<h3>Scroll Page</h3>

<pre><code>driver.execute_script(

    "window.scrollTo(0, document.body.scrollHeight);"

)</code></pre>

<h3>Scroll to Element</h3>

<pre><code>element = driver.find_element(

    By.ID,

    "footer"

)

 

driver.execute_script(

    "arguments[0].scrollIntoView();",

    element

)</code></pre>

<p>JavaScript should generally complement normal Selenium interactions rather than automatically replacing them.</p>

<hr>

<h2>44. Taking Screenshots</h2>

<p>Screenshots are useful when debugging failed automation steps.</p>

<pre><code>driver.save_screenshot(

    "homepage.png"

)</code></pre>

<h3>Screenshot on Failure</h3>

<pre><code>try:

    driver.find_element(

        By.ID,

        "submit"

    ).click()

except Exception:

    driver.save_screenshot(

        "failure.png"

    )

    raise</code></pre>

<hr>

<h2>45. Exception Handling in Selenium Scripts</h2>

<p>Selenium scripts interact with browsers and dynamic applications, so exceptions can occur during element lookup, interaction, synchronization, frame switching, window switching, and browser operations.</p>

<pre><code>from selenium.common.exceptions import (

    NoSuchElementException,

    TimeoutException,

    WebDriverException

)

 

try:

    element = WebDriverWait(

        driver,

        10

    ).until(

        EC.element_to_be_clickable(

            (By.ID, "submit")

        )

    )

 

    element.click()

 

except TimeoutException:

    print("Element did not become clickable")

 

except NoSuchElementException:

    print("Element was not found")

 

except WebDriverException as e:

    print("WebDriver error:", e)</code></pre>

<h2>46. Using finally for Browser Cleanup</h2>

<pre><code>driver = None

 

try:

    driver = webdriver.Chrome()

    driver.get("https://example.com")

    # Test steps

finally:

    if driver:

        driver.quit()</code></pre>

<p>Calling <code>quit()</code> ends the WebDriver session and closes the browser session.</p>

<hr>

<h2>47. Logging Selenium Script Execution</h2>

<pre><code>import logging

 

logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s - %(levelname)s - %(message)s"

)

 

logging.info("Starting Selenium script")

 

driver = webdriver.Chrome()

 

logging.info("Browser started")

 

driver.get("https://example.com")

 

logging.info("Application opened")</code></pre>

<h2>48. Logging Test Steps</h2>

<pre><code>logging.info("Entering username")

username.send_keys("admin")

 

logging.info("Entering password")

password.send_keys("admin123")

 

logging.info("Clicking login button")

login_button.click()

 

logging.info("Login operation completed")</code></pre>

<hr>

<h2>49. Building a Complete Selenium Script</h2>

<p>A professional Selenium script should combine browser initialization, navigation, locators, actions, waits, validation, exception handling, logging, screenshots, and cleanup.</p>

<pre><code>import logging

 

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.common.exceptions import (

    TimeoutException,

    WebDriverException

)

 

logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s - %(levelname)s - %(message)s"

)

 

driver = None

 

try:

    logging.info("Starting browser")

 

    driver = webdriver.Chrome()

 

    driver.get(

        "https://example.com/login"

    )

 

    wait = WebDriverWait(driver, 10)

 

    logging.info("Finding username field")

 

    username = wait.until(

        EC.visibility_of_element_located(

            (By.ID, "username")

        )

    )

 

    logging.info("Finding password field")

 

    password = wait.until(

        EC.visibility_of_element_located(

            (By.ID, "password")

        )

    )

 

    logging.info("Finding login button")

 

    login_button = wait.until(

        EC.element_to_be_clickable(

            (By.ID, "login")

        )

    )

 

    username.send_keys("admin")

    password.send_keys("admin123")

    login_button.click()

 

    wait.until(

        EC.url_contains("/dashboard")

    )

 

    assert "/dashboard" in driver.current_url

 

    logging.info(

        "Login test completed successfully"

    )

 

except TimeoutException as e:

    logging.error(

        "Timeout occurred: %s",

        e

    )

 

    if driver:

        driver.save_screenshot(

            "timeout_failure.png"

        )

 

except WebDriverException as e:

    logging.error(

        "WebDriver error: %s",

        e

    )

 

    if driver:

        driver.save_screenshot(

            "webdriver_failure.png"

        )

 

finally:

    if driver:

        driver.quit()

        logging.info("Browser closed")</code></pre>

<hr>

<h2>50. Building a Search Script</h2>

<p>A search automation script typically opens a search page, enters a search term, submits the search, waits for results, and validates the results.</p>

<pre><code>from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

driver = webdriver.Chrome()

 

try:

    driver.get(

        "https://example.com/search"

    )

 

    search_box = WebDriverWait(

        driver,

        10

    ).until(

        EC.visibility_of_element_located(

            (By.NAME, "q")

        )

    )

 

    search_box.clear()

 

    search_box.send_keys(

        "Selenium Python"

    )

 

    search_box.send_keys(Keys.ENTER)

 

    results = WebDriverWait(

        driver,

        10

    ).until(

        EC.presence_of_all_elements_located(

            (By.CSS_SELECTOR, ".result")

        )

    )

 

    print("Results:", len(results))

 

finally:

    driver.quit()</code></pre>

<hr>

<h2>51. Building an E-Commerce Selenium Script</h2>

<p>An e-commerce workflow can be automated by creating a sequence of browser operations.</p>

<pre><code>Open Website

    |

    v

Login

    |

    v

Search Product

    |

    v

Select Product

    |

    v

Add to Cart

    |

    v

Open Cart

    |

    v

Verify Product

    |

    v

Proceed to Checkout

    |

    v

Verify Checkout

    |

    v

Logout</code></pre>

<h3>Example</h3>

<pre><code>search = WebDriverWait(driver, 10).until(

    EC.visibility_of_element_located(

        (By.ID, "search")

    )

)

 

search.send_keys("Laptop")

search.send_keys(Keys.ENTER)

 

product = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable(

        (By.CSS_SELECTOR, ".product-card")

    )

)

 

product.click()

 

add_to_cart = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable(

        (By.ID, "add-to-cart")

    )

)

 

add_to_cart.click()</code></pre>

<hr>

<h2>52. Building a Registration Script</h2>

<pre><code>from selenium import webdriver

from selenium.webdriver.common.by import By

 

driver = webdriver.Chrome()

 

try:

    driver.get(

        "https://example.com/register"

    )

 

    driver.find_element(

        By.ID,

        "name"

    ).send_keys("John")

 

    driver.find_element(

        By.ID,

        "email"

    ).send_keys("[email protected]")

 

    driver.find_element(

        By.ID,

        "password"

    ).send_keys("Password123")

 

    driver.find_element(

        By.ID,

        "confirm-password"

    ).send_keys("Password123")

 

    driver.find_element(

        By.ID,

        "register"

    ).click()

 

finally:

    driver.quit()</code></pre>

<hr>

<h2>53. Building a Reusable Function</h2>

<p>Instead of repeating the same Selenium operations throughout a project, common actions can be placed into reusable functions.</p>

<pre><code>def enter_text(driver, locator, value):

    element = WebDriverWait(

        driver,

        10

    ).until(

        EC.visibility_of_element_located(locator)

    )

 

    element.clear()

    element.send_keys(value)</code></pre>

<h3>Using the Function</h3>

<pre><code>enter_text(

    driver,

    (By.ID, "username"),

    "admin"

)

 

enter_text(

    driver,

    (By.ID, "password"),

    "admin123"

)</code></pre>

<h2>54. Reusable Click Function</h2>

<pre><code>def click_element(driver, locator):

    element = WebDriverWait(

        driver,

        10

    ).until(

        EC.element_to_be_clickable(locator)

    )

 

    element.click()</code></pre>

<h3>Using the Function</h3>

<pre><code>click_element(

    driver,

    (By.ID, "login")

)</code></pre>

<hr>

<h2>55. Page Object Model</h2>

<p>The Page Object Model, commonly called POM, separates page-specific locators and interactions from test logic. This reduces duplication and makes large Selenium projects easier to maintain.</p>

<h3>Example Login Page</h3>

<pre><code>from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

class LoginPage:

    USERNAME = (By.ID, "username")

    PASSWORD = (By.ID, "password")

    LOGIN_BUTTON = (By.ID, "login")

 

    def __init__(self, driver):

        self.driver = driver

        self.wait = WebDriverWait(

            driver,

            10

        )

 

    def login(self, username, password):

        self.wait.until(

            EC.visibility_of_element_located(

                self.USERNAME

            )

        ).send_keys(username)

 

        self.wait.until(

            EC.visibility_of_element_located(

                self.PASSWORD

            )

        ).send_keys(password)

 

        self.wait.until(

            EC.element_to_be_clickable(

                self.LOGIN_BUTTON

            )

        ).click()</code></pre>

<h2>56. Test Using Page Object</h2>

<pre><code>def test_login(driver):

    login_page = LoginPage(driver)

 

    login_page.login(

        "admin",

        "admin123"

    )

 

    assert "/dashboard" in driver.current_url</code></pre>

<hr>

<h2>57. Using pytest with Selenium</h2>

<p>Pytest is commonly used as a Python test runner for organizing and executing Selenium test cases.</p>

<h3>Installation</h3>

<pre><code>pip install pytest</code></pre>

<h3>Simple Test</h3>

<pre><code>from selenium import webdriver

 

def test_homepage_title():

    driver = webdriver.Chrome()

 

    try:

        driver.get(

            "https://example.com"

        )

 

        assert "Example" in driver.title

 

    finally:

        driver.quit()</code></pre>

<p>Pytest can be used to organize Selenium tests into maintainable test suites.</p>

<hr>

<h2>58. Using pytest Fixtures</h2>

<p>Fixtures can be used to create and clean up browser sessions.</p>

<pre><code>import pytest

from selenium import webdriver

 

@pytest.fixture

def driver():

    browser = webdriver.Chrome()

    yield browser

    browser.quit()</code></pre>

<h3>Using the Fixture</h3>

<pre><code>def test_title(driver):

    driver.get(

        "https://example.com"

    )

 

    assert "Example" in driver.title</code></pre>

<hr>

<h2>59. Separating Test Data</h2>

<p>Test data should ideally be separated from test logic when the same workflow needs to run with multiple datasets.</p>

<pre><code>users = [

    ("admin", "admin123"),

    ("user1", "user123"),

    ("tester", "test123")

]

 

for username, password in users:

    print(username, password)</code></pre>

<h2>60. Data-Driven Selenium Concept</h2>

<pre><code>Test Data

    |

    +-- User 1

    |

    +-- User 2

    |

    +-- User 3

    |

    v

Same Selenium Workflow

    |

    v

Different Test Results</code></pre>

<hr>

<h2>61. Organizing Selenium Scripts</h2>

<p>Small Selenium scripts can be maintained in a single Python file, but larger automation projects should separate tests, page objects, utilities, configuration, test data, screenshots, and reports.</p>

<h3>Suggested Project Structure</h3>

<pre><code>selenium_project/

|

+-- tests/

|   +-- test_login.py

|   +-- test_search.py

|   +-- test_cart.py

|

+-- pages/

|   +-- login_page.py

|   +-- home_page.py

|   +-- product_page.py

|   +-- cart_page.py

|

+-- utilities/

|   +-- wait_helper.py

|   +-- screenshot_helper.py

|   +-- logger.py

|

+-- test_data/

|   +-- users.json

|   +-- products.json

|

+-- screenshots/

|

+-- reports/

|

+-- conftest.py

|

+-- requirements.txt</code></pre>

<h2>62. requirements.txt</h2>

<pre><code>selenium

pytest</code></pre>

<p>Install project dependencies with:</p>

<pre><code>pip install -r requirements.txt</code></pre>

<hr>

<h2>63. Building a Selenium Script Step by Step</h2>

<ol>

<li>Install Python.</li>

<li>Install Selenium.</li>

<li>Install a supported browser.</li>

<li>Create a Python file.</li>

<li>Import Selenium.</li>

<li>Create the WebDriver.</li>

<li>Open the application URL.</li>

<li>Identify required web elements.</li>

<li>Select stable locators.</li>

<li>Add appropriate waits.</li>

<li>Perform browser actions.</li>

<li>Validate expected results.</li>

<li>Add exception handling.</li>

<li>Add logging and screenshots.</li>

<li>Close the browser.</li>

<li>Execute the script using Python or a test runner.</li>

</ol>

<h2>64. Complete Script Development Flow</h2>

<pre><code>Requirement

    |

    v

Test Scenario

    |

    v

Test Steps

    |

    v

Identify Web Elements

    |

    v

Choose Locators

    |

    v

Write Selenium Commands

    |

    v

Add Wait Strategy

    |

    v

Add Assertions

    |

    v

Add Exception Handling

    |

    v

Add Logging

    |

    v

Execute Test

    |

    v

Analyze Result

    |

    v

Maintain Script</code></pre>

<hr>

<h2>65. Common Mistakes While Building Selenium Scripts</h2>

<h3>Mistake 1: Using Incorrect Locators</h3>

<pre><code>driver.find_element(

    By.ID,

    "wrong-id"

)</code></pre>

<p>Always verify that the locator actually identifies the intended element.</p>

<h3>Mistake 2: Using Hardcoded Delays Everywhere</h3>

<pre><code>time.sleep(10)</code></pre>

<p>Prefer condition-based waits when the required browser state can be defined.</p>

<h3>Mistake 3: Ignoring Dynamic Content</h3>

<p>Modern applications can update the DOM after the initial page load. Scripts should account for these state changes.</p>

<h3>Mistake 4: Using Unstable XPath</h3>

<pre><code>/html/body/div[2]/div[3]/div[1]/button</code></pre>

<p>Long positional XPath expressions can be fragile when the page structure changes.</p>

<h3>Mistake 5: Not Closing the Browser</h3>

<pre><code>driver = webdriver.Chrome()

driver.get("https://example.com")

# No cleanup</code></pre>

<p>Use appropriate teardown or <code>finally</code> logic.</p>

<h3>Mistake 6: Catching Every Exception</h3>

<pre><code>try:

    ...

except:

    pass</code></pre>

<p>This can hide important failures and make debugging difficult.</p>

<h3>Mistake 7: Putting Everything in One Large Function</h3>

<p>Large scripts become difficult to maintain. Use functions, page objects, utilities, and test fixtures as the project grows.</p>

<hr>

<h2>66. Best Practices for Building Selenium Scripts</h2>

<ul>

<li>Use meaningful variable and function names.</li>

<li>Use stable locators.</li>

<li>Prefer explicit waits for dynamic conditions.</li>

<li>Avoid unnecessary hardcoded sleeps.</li>

<li>Keep test data separate from automation logic.</li>

<li>Use Page Object Model for larger projects.</li>

<li>Use reusable helper functions.</li>

<li>Use assertions for important expected results.</li>

<li>Handle exceptions appropriately.</li>

<li>Capture screenshots for important failures.</li>

<li>Use logging instead of relying only on print statements.</li>

<li>Keep browser cleanup in teardown or finally blocks.</li>

<li>Do not silently ignore exceptions.</li>

<li>Keep tests independent where practical.</li>

<li>Use a test runner for larger test suites.</li>

<li>Keep the automation project organized.</li>

<li>Review and maintain locators when the UI changes.</li>

</ul>

<h2>67. Good Script vs Poor Script</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Poor Practice</th><th>Better Practice</th></tr>

<tr><td>Long hardcoded XPath</td><td>Stable ID, name, CSS, or concise XPath</td></tr>

<tr><td>Repeated code</td><td>Reusable functions or page objects</td></tr>

<tr><td>Only sleep()</td><td>Condition-based waits</td></tr>

<tr><td>No assertions</td><td>Validate expected results</td></tr>

<tr><td>Empty except block</td><td>Log or properly handle exceptions</td></tr>

<tr><td>No cleanup</td><td>Use teardown or finally</td></tr>

<tr><td>One huge script</td><td>Modular project structure</td></tr>

<tr><td>Hardcoded test data everywhere</td><td>Separate test data</td></tr>

</table>

<hr>

<h2>68. Practical Project: Automated Login Test</h2>

<p>Create a complete Selenium Python script that tests a login workflow.</p>

<h3>Requirements</h3>

<ol>

<li>Open the login page.</li>

<li>Verify the page title.</li>

<li>Locate the username field.</li>

<li>Locate the password field.</li>

<li>Enter valid credentials.</li>

<li>Click the login button.</li>

<li>Wait for the dashboard.</li>

<li>Verify the dashboard URL or heading.</li>

<li>Capture a screenshot if the test fails.</li>

<li>Close the browser.</li>

</ol>

<h3>Expected Flow</h3>

<pre><code>Open Login Page

      |

      v

Verify Title

      |

      v

Enter Username

      |

      v

Enter Password

      |

      v

Click Login

      |

      v

Wait for Dashboard

      |

      v

Validate Dashboard

      |

      v

Pass / Fail

      |

      v

Cleanup</code></pre>

<hr>

<h2>69. Practical Project: Automated Search Test</h2>

<p>Build a search automation script that:</p>

<ol>

<li>Opens the website.</li>

<li>Finds the search box.</li>

<li>Enters a search term.</li>

<li>Submits the search.</li>

<li>Waits for search results.</li>

<li>Counts result elements.</li>

<li>Validates that results are displayed.</li>

<li>Captures a screenshot on failure.</li>

</ol>

<h2>70. Practical Project: E-Commerce Cart Test</h2>

<p>Create a script that automates a complete shopping workflow.</p>

<pre><code>Open Store

    |

    v

Login

    |

    v

Search Product

    |

    v

Open Product

    |

    v

Add Product to Cart

    |

    v

Open Cart

    |

    v

Verify Product

    |

    v

Verify Quantity

    |

    v

Verify Price

    |

    v

Proceed to Checkout</code></pre>

<hr>

<h2>71. Practical Project: Registration Test</h2>

<p>Automate a registration form containing:</p>

<ul>

<li>First name.</li>

<li>Last name.</li>

<li>Email.</li>

<li>Password.</li>

<li>Confirm password.</li>

<li>Gender.</li>

<li>Country.</li>

<li>Terms checkbox.</li>

<li>Register button.</li>

</ul>

<p>The script should validate the success message after registration.</p>

<hr>

<h2>72. Practical Project: Complete Regression Workflow</h2>

<p>A larger Selenium project can combine multiple workflows.</p>

<pre><code>Test Suite

    |

    +-- Login Test

    |

    +-- Search Test

    |

    +-- Product Test

    |

    +-- Cart Test

    |

    +-- Checkout Test

    |

    +-- Logout Test

    |

    v

Generate Test Results</code></pre>

<h2>73. Selenium Script Execution</h2>

<p>A standalone Python Selenium script can be executed from the terminal using Python.</p>

<pre><code>python test_login.py</code></pre>

<p>For pytest-based projects:</p>

<pre><code>pytest test_login.py</code></pre>

<hr>

<h2>74. Debugging Selenium Scripts</h2>

<p>When a Selenium script fails, investigate the failure systematically.</p>

<ol>

<li>Read the exception message.</li>

<li>Identify the failing line.</li>

<li>Check the current URL.</li>

<li>Check the page title.</li>

<li>Inspect the HTML element.</li>

<li>Verify the locator.</li>

<li>Check whether a frame is involved.</li>

<li>Check whether a new window is involved.</li>

<li>Check whether an alert is blocking the page.</li>

<li>Check the synchronization strategy.</li>

<li>Capture a screenshot.</li>

<li>Review logs.</li>

</ol>

<h3>Useful Debug Information</h3>

<pre><code>print("URL:", driver.current_url)

print("Title:", driver.title)

print("Handles:", driver.window_handles)

print("Source length:", len(driver.page_source))</code></pre>

<hr>

<h2>75. Selenium Script Maintenance</h2>

<p>Web applications change frequently. A locator that works today may stop working after a UI redesign. Therefore, Selenium scripts require regular maintenance.</p>

<h3>Maintenance Checklist</h3>

<ul>

<li>Review broken locators.</li>

<li>Remove duplicate code.</li>

<li>Update waits when application behavior changes.</li>

<li>Remove obsolete test data.</li>

<li>Update browser and Selenium versions as required.</li>

<li>Review exception handling.</li>

<li>Review screenshots and logs.</li>

<li>Remove unnecessary workarounds.</li>

<li>Keep Page Objects synchronized with the application.</li>

</ul>

<hr>

<h2>76. Interview Questions on Building Selenium Scripts</h2>

<h3>Q1. What is a Selenium script?</h3>

<p>A Selenium script is a program that uses Selenium WebDriver to automate browser interactions and validate web application behavior.</p>

<h3>Q2. What are the basic steps of a Selenium script?</h3>

<p>Start the WebDriver, open the URL, locate elements, perform actions, validate results, handle failures, and close the browser.</p>

<h3>Q3. How do you launch Chrome using Selenium Python?</h3>

<pre><code>from selenium import webdriver

 

driver = webdriver.Chrome()</code></pre>

<h3>Q4. How do you open a website?</h3>

<pre><code>driver.get("https://example.com")</code></pre>

<h3>Q5. How do you locate an element?</h3>

<pre><code>element = driver.find_element(

    By.ID,

    "username"

)</code></pre>

<h3>Q6. How do you enter text?</h3>

<pre><code>element.send_keys("Selenium")</code></pre>

<h3>Q7. How do you click a button?</h3>

<pre><code>button.click()</code></pre>

<h3>Q8. How do you retrieve element text?</h3>

<pre><code>print(element.text)</code></pre>

<h3>Q9. Why are waits important?</h3>

<p>Waits synchronize the script with the application's current browser state and reduce failures caused by timing differences.</p>

<h3>Q10. What is Page Object Model?</h3>

<p>POM is a design approach that organizes page locators and page interactions into dedicated classes.</p>

<h3>Q11. Why use assertions?</h3>

<p>Assertions verify whether actual application behavior matches the expected result.</p>

<h3>Q12. Why use finally?</h3>

<p>The finally block can be used to ensure browser cleanup occurs whether the script succeeds or fails.</p>

<h3>Q13. What is the difference between close() and quit()?</h3>

<p><code>close()</code> closes the current browser window or tab, while <code>quit()</code> ends the WebDriver session and closes the browser session.</p>

<h3>Q14. How do you handle a dynamic element?</h3>

<p>Use an appropriate locator and synchronization strategy, commonly an explicit wait for the required condition.</p>

<h3>Q15. How do you make Selenium scripts maintainable?</h3>

<p>Use stable locators, reusable functions, Page Object Model, test data separation, explicit waits, logging, exception handling, and a structured project layout.</p>

<hr>

<h2>77. Quick Revision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Command / Concept</th><th>Purpose</th></tr>

<tr><td><code>webdriver.Chrome()</code></td><td>Creates Chrome WebDriver.</td></tr>

<tr><td><code>driver.get()</code></td><td>Opens a URL.</td></tr>

<tr><td><code>driver.title</code></td><td>Returns page title.</td></tr>

<tr><td><code>driver.current_url</code></td><td>Returns current URL.</td></tr>

<tr><td><code>find_element()</code></td><td>Finds one element.</td></tr>

<tr><td><code>find_elements()</code></td><td>Finds multiple elements.</td></tr>

<tr><td><code>send_keys()</code></td><td>Enters text or keyboard commands.</td></tr>

<tr><td><code>click()</code></td><td>Clicks an element.</td></tr>

<tr><td><code>clear()</code></td><td>Clears an input.</td></tr>

<tr><td><code>text</code></td><td>Gets rendered element text.</td></tr>

<tr><td><code>get_attribute()</code></td><td>Gets an element attribute/property value.</td></tr>

<tr><td><code>WebDriverWait</code></td><td>Waits for a condition.</td></tr>

<tr><td><code>EC</code></td><td>Provides expected conditions.</td></tr>

<tr><td><code>assert</code></td><td>Validates expected behavior.</td></tr>

<tr><td><code>save_screenshot()</code></td><td>Captures browser screenshot.</td></tr>

<tr><td><code>driver.quit()</code></td><td>Ends the WebDriver session.</td></tr>

</table>

<h2>78. Recommended Selenium Script Structure</h2>

<pre><code>Imports

   |

   v

Configuration

   |

   v

Driver Setup

   |

   v

Test Data

   |

   v

Open Application

   |

   v

Page Interaction

   |

   v

Synchronization

   |

   v

Validation

   |

   v

Exception Handling

   |

   v

Logging

   |

   v

Screenshot on Failure

   |

   v

Teardown</code></pre>

<h2>79. Professional Selenium Automation Flow</h2>

<pre><code>Requirement

    |

    v

Test Case Design

    |

    v

Python Test Script

    |

    v

Page Objects

    |

    v

Reusable Utilities

    |

    v

WebDriver

    |

    v

Browser

    |

    v

Web Application

    |

    v

Expected Result

    |

    v

Assertion

    |

    +------ Pass

    |

    +------ Fail

              |

              v

        Log + Screenshot

              |

              v

          Test Report</code></pre>

<hr>

<h2>80. Final Summary</h2>

<p>Building Selenium Scripts with Python involves much more than simply opening a browser and clicking elements. A reliable Selenium script combines WebDriver initialization, navigation, element location, browser and element operations, synchronization, validation, exception handling, logging, screenshots, and cleanup.</p>

<p>Selenium scripting commonly involves starting the browser session, navigating to a page, finding elements, performing actions, requesting browser or element information, establishing a waiting strategy, validating results, and ending the session.</p>

<p>For small automation tasks, a simple Python script may be sufficient. For larger projects, the script should be organized using Page Object Model, reusable utilities, fixtures, test data, logging, reporting, and a structured project architecture.</p>

<p>The main goal of professional Selenium scripting is to create automation that is <strong>reliable, readable, reusable, maintainable, debuggable, and scalable</strong>.</p>

<h2>81. Course Resources</h2>

<p><strong>Selenium Training:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">https://www.justacademy.co/course-detail/selenium-training</a></p>

<p><strong>Register for Course Demo:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">https://www.justacademy.co/register-for-course-demo</a></p>

</div>

Previous Next
whatsapp